# -*- coding: utf-8 -*-
#!/usr/bin/env python
# encoding: utf-8
"""
views.py

Created by 姚 远 on 2010-04-15.
Copyright (c) 2010 knarfytrebil. All rights reserved.
"""
#import from google apps engine
from google.appengine.ext import db
from google.appengine.ext.db import *
from google.appengine.ext import webapp
from google.appengine.ext.webapp import util
from google.appengine.ext.webapp \
	import template
#django
from django.utils import simplejson as json
#python library
import urllib2,time,datetime,urllib,string
from datetime import datetime
from datetime import timedelta
#system and so on
import sys,os
import socket
import string
#Models
from models import Blog,Topics,Events,Users
#then we are going to import something else, and this involves with some nasty stuff
current_dir = os.path.abspath(os.path.dirname(__file__))
sys.path = [current_dir] + sys.path
#finished adding current path to sys.path
from app import lib
#imported my library
class TopicHandler(webapp.RequestHandler):
	def get(self):
		req_id = self.request.get('topic_id')
		global req_id
		rows = []
		query = db.GqlQuery('SELECT * FROM Topics WHERE topic_id = :1 ORDER BY updated DESC',int(req_id))
		rows = query.fetch(10)
		if len(rows) != 1:
			topthread = rows.pop(1)
		else:
			topthread = rows.pop(0)
		rows.reverse()
		topics = []
		for row in rows:
			topics.append(row)
		path = lib.genpath('/html/templates','content.html')
		values_user = lib.get_usr(str(self.__class__.__name__)[:-7],"",topthread.lang,req_id)
		#gen title
		username = values_user['nickname']
		global username
		values = lib.def_title(str(topthread.lang))
		values_forum = lib.def_forum('common',str(topthread.lang))
		values.update(values_forum)
		values.update(values_user)
		values['topics'] = topics
		values['topthread'] = topthread
		self.response.out.write(template.render(path, values))
	def post(self):
		body = self.request.get('body')
		query = Topics.gql('WHERE topic_id = :1 AND depth = 0',int(req_id))
		row = query.get()
		row.updated = datetime.now()
		row.put()
		# query = db.GqlQuery('SELECT * FROM Topics WHERE topic_id = :1 ORDER BY updated DESC', req_id)
		# row = query.get()
		topics = Topics(kind_id = 0,
			lang = "",
			title = "",
			body = body,
			depth = 1,
			topic_id = int(req_id),
			author = username)
		topics.put()
		path = lib.genpath('/html/templates','redirect.html')
		self.response.out.write(template.render(path,''))
	
class ForumHandler(webapp.RequestHandler):
	def get(self):
		#initiate the board
		req_lang = str(self.request.get('lang'))
		req_board = str(self.request.get('board'))
		#make the instance global
		global req_lang,req_board
		#init fetch
		rows = []
		query = db.GqlQuery('SELECT * FROM Topics WHERE lang = :1 AND kind_id = :2 AND depth = 0 ORDER BY updated DESC',req_lang,lib.gen_forum_kind(req_board))
		rows = query.fetch(10)
		topics = []
		if rows != []:
			for row in rows:
				topics.append(row)
		else:
			topics = [lib.call_none_msg(req_lang)[0]]
		path = lib.genpath('/html/templates/','common.html')
		#gen title
		values_user = lib.get_usr(str(self.__class__.__name__)[:-7],req_board,req_lang,"")
		username = values_user['nickname']
		global username
		values = lib.def_title(req_lang)
		values_forum = lib.def_forum(req_board,req_lang)
		values.update(values_forum)
		values.update(values_user)
		values['topics'] = topics
		self.response.out.write(template.render(path, values))
	def post(self):
		title = self.request.get('title')
		body = self.request.get('body')
		query = db.GqlQuery('SELECT * FROM Topics ORDER BY topic_id DESC')
		row = query.get()
		if row is None:
			topic_id = 0
		else:
			topic_id = row.topic_id + 1
		topics = Topics(kind_id = lib.gen_forum_kind(req_board),
			lang = req_lang,
			title = title,
			body = body,
			created = datetime.now(),
			depth = 0,
			topic_id = topic_id,
			author = username)
		topics.put()
		path = lib.genpath('/html/templates','redirect.html')
		self.response.out.write(template.render(path,''))
class IndexHandler(webapp.RequestHandler):
	def get(self):
		req_lang = str(self.request.get('lang'))
		if req_lang == "":
			path = lib.genpath('/html/templates','top.html')
			self.response.out.write(template.render(path,""))
			return
		##initiating
		values_user = lib.get_usr(str(self.__class__.__name__)[:-7],"",req_lang,"")
		m = [[],[],[]]
		rows = []
		#############
		##  Start  ##
		#############
		query = db.GqlQuery('SELECT * FROM Blog WHERE depth = 0 AND lang = :1 ORDER BY updated DESC',req_lang)
		rows = query.fetch(10)
		blogs = []
		if rows == []:
			blogs = lib.call_none_msg(req_lang)
		else:
			for row in rows:
				#mon = str(row[1])[5:7]
				#tm = str(row[1])[-8:]
				#dayy = str(row[1])[-11:-8]
				#dic_mon = {'01':'Jan','02':'Feb','03':'Mar','04':'Apr','05':'May',
				#	'06':'Jun','07':'Jul','08':'Aug','09':'Sep','10':'Oct','11':'Nov',
				#	'12':'Dec'}
				#mon = dic_mon[mon]
				#blogs.append( str(row[0]) + "<em>{</em><li>" + str(row[2]) + 
				#	"</li>" + "<li><span id ='mon'>" + mon  + "<span id ='dayy'>" + dayy + "</span></span><span id ='tm'>"+ tm + "</span></li><p><em>}</em>" + 
				#	"<a href = 'http://211.6.189.194:8888/titan/contents?id=" + str(row[3])
				#	+ "'>" + reply_text + "</a><em>{</em></p>")
				blogs.append(row)
			row = ""
			query = ""
		##############################
		###     Finishing unload    ##
		###  and yet starting again ##
		##############################
		n = ['common','translation','fml']
		for i in range (1,4):
			query = db.GqlQuery('SELECT * FROM Topics WHERE kind_id = :1 AND depth = 0 AND lang = :2 ORDER BY updated DESC',i-1,req_lang)
			rows = query.fetch(5)
			if rows != []:
				for row in rows:
					m[i-1].append(row)
			else:
				m[i-1] = lib.call_none_msg(req_lang)
			rows = []
			query = ""
		query = db.GqlQuery('SELECT * FROM Events WHERE lang = :1 ORDER BY updated DESC',req_lang)
		row = query.get()
		event = row
		#####################################
		###   End of loading all the shit ###
		#####################################
		path = lib.genpath('/html/templates/','index.html')
		values = lib.def_title(req_lang)
		values_index = lib.def_index(req_lang)
		values.update(values_index)
		values.update(values_user)
		values['blogs'] = blogs
		values['events'] = event
		values['translation_heads'] = m[1]
		values['forum_heads'] = m[0]
		values['fml_heads'] = m[2]
		self.response.out.write(template.render(path, values))
class UserPageHandler(webapp.RequestHandler):
	def get(self):
		req_id = str(self.request.get('id'))
		req_lang = str(self.request.get('lang'))
		global req_id
		values = lib.def_title(req_lang)
		values_usr = lib.def_user(req_id)
		user = users.get_current_user()
		global user
		me = False
		if user.nickname() == req_id:me = True
		values.update(values_usr)
		values['me'] = me
		path = lib.genpath('/html/templates/','account.html')
		self.response.out.write(template.render(path, values))
	def post(self):
		blog_title = self.request.get('blog_title')
		blog_body = self.request.get('blog_body')
		event_title = self.request.get('event_title')
		event_body = self.request.get('event_body')
	 	blog_language = self.request.get('blog_language')
		event_language = self.request.get('event_language')
		tsubu = self.request.get('tsubu')
		gender = self.request.get('gender')
		cell = self.request.get('cell')
		twitter = self.request.get('twitter')
		facebook = self.request.get('facebook')
		submit_list = [
				[blog_title,blog_language,blog_body],
				[event_title,event_language,event_body],
				[tsubu],
				[gender,cell,twitter,facebook]
			]
		for i in range(0,len(submit_list)):
			lsts = ''.join(submit_list[i])
			if lsts != '':
				if i == 0:
					query = db.GqlQuery('SELECT * FROM Blog WHERE depth = 0 ORDER BY updated DESC')
					row = query.get()
					if row is None:
						new_blg_id = 0
					else:
						new_blg_id = row.blg_id + 1
					blog = Blog(
						blg_id = new_blg_id,
						author = user.nickname(),
						lang = blog_language,
						title = blog_title,
						body = blog_body,
						depth = 0,
						)
					blog.put()
					#blog
				elif i == 1:
					query = db.GqlQuery('SELECT * FROM Events ORDER BY updated DESC')
					row = query.get()
					if row is None:
						new_event_id = 0
					else:
						new_event_id = row.event_id + 1
					event = Events(
						event_id = new_event_id,
						lang = event_language,
						title = event_title,
						body = event_body,
						)
					event.put()
					#event
				elif i == 2:
					user_query = Users.gql('WHERE nickname = :1',user.nickname())
					user_result = user_query.get()
					user_result.tsubu = db.Text(tsubu)
					user_result.put()
					#tsubu
				elif i == 3:
					user_query = Users.gql('WHERE nickname = :1',user.nickname())
					user_result = user_query.get()
					user_result.gender = int(gender)
					user_result.twitter = db.Text(twitter)
					user_result.cell = db.PhoneNumber(cell)
					user_result.facebook = db.Text(facebook)
					user_result.put()
					#user
		path = lib.genpath('/html/templates','redirect.html')
		self.response.out.write(template.render(path,''))
class CommunityHandler(webapp.RequestHandler):
	def get(self):
		req_lang = str(self.request.get('lang'))
		values = lib.def_title(req_lang)
		path = lib.genpath('/html/templates/static','community-' + req_lang + '.html')
		self.response.out.write(template.render(path, values))
class EventHandler(webapp.RequestHandler):
	def get(self):
		req_lang = str(self.request.get('lang'))
		query = db.GqlQuery("SELECT * FROM Events WHERE lang = :1 ORDER BY updated DESC",req_lang)
		row = query.get()
		values = lib.def_title(req_lang)
		values['events'] = row
		path = lib.genpath('/html/templates','event.html')
		self.response.out.write(template.render(path, values))
class BlogHandler(webapp.RequestHandler):
	def get(self):
		req_id = int(self.request.get('id'))
		req_lang = str(self.request.get('lang'))
		values = lib.def_title(req_lang)
		query = Blog.gql('WHERE blg_id = :1 AND depth = 0',req_id)
		row = query.get()
		global row
		values['blog'] = row
		query = Blog.gql('WHERE blg_id = :1 AND depth = 1',req_id)
		rows = query.fetch(300)
		values['replys'] = rows
		path = lib.genpath('/html/templates','blog.html')
		user = users.get_current_user()
		if user:
			is_user = True
			username = user.nickname()
			global username
		else:
			is_user = False
		self.response.out.write(template.render(path, values))
	def post(self):
		comment = self.request.get('comment')
		reply = Blog(
			blg_id = row.blg_id,
			author = username,
			body = comment,
			depth = 1,
			)
		reply.put()
		auth = tweepy.BasicAuthHandler('watchoku', 'useradmin')
		api = tweepy.API(auth)
		try:
			api.update_status(comment[:130])
		except Exception, e:
			pass
		path = lib.genpath('/html/templates','redirect.html')
		self.response.out.write(template.render(path,''))